﻿using System.Data;
using U8DllPack.Controller;
using U8DllPack.Model;
using U8DllPack.Properties;

namespace U8DllPack.View
{
    public partial class FrmEdit : Form
    {

        public Json_Project? UiProject { get; set; }
        private int btncloseX;
        private int btnsaveX;
        public FrmEdit()
        {
            InitializeComponent();
            Icon = Resources.pack_32;
            btncloseX = panBtn.Width - btnClose.Right + btnClose.Width;
            btnsaveX = panBtn.Width - btnSave.Right + btnSave.Width;
        }

        private void FrmEdit_Load(object sender, EventArgs e)
        {
            dgvList.AutoGenerateColumns = false;
            Sub_Load();
        }

        private void Sub_Load()
        {
            DataTable dt = CustomDataTable.DT_U8ver();
            col_U8ver.DataSource = dt;
            col_U8ver.DisplayMember = "Text";
            col_U8ver.ValueMember = "Id";
            Sub_LoadDatas();
        }

        private void Sub_LoadDatas()
        {
            DataTable dt = CustomDataTable.ReturnDPDT();
            UiProject ??= new Json_Project();

            if (UiProject.Id != null && !UiProject.projectfile.IsNullOrWhiteSpace())
            {
                string json = BaseCls.ReadLibsJson(UiProject.projectfile!);
                if (json.IsNullOrWhiteSpace()) return;
                Json_ProjectInfo? ProjectInfo = JsonHelper.Deserialize<Json_ProjectInfo>(json);
                if (ProjectInfo != null)
                {
                    txtProjectname.Enabled = false;
                    txtSystempath.Enabled = false;
                    txtProjectname.Text = UiProject.projectname;
                    txtSystempath.Text = ProjectInfo.systempath;
                    txtVer.Text = ProjectInfo.ver;
                    txtDesc.Text = ProjectInfo.desc;

                    if (ProjectInfo.dlls != null && ProjectInfo.dlls.Count > 0)
                    {
                        foreach (Json_ProjectDlls dll in ProjectInfo.dlls)
                        {
                            dt.Rows.Add([dll.u8ver, dll.respath, dll.filepath, dll.name, dll.ver, dll.desc]);
                        }
                    }
                }
            }
            dgvList.DataSource = dt;
            dt.DefaultView.Sort = "u8ver asc,name asc";
        }

        private void FrmEdit_Resize(object sender, EventArgs e)
        {
            btnClose.Left = panBtn.Width - btncloseX;
            btnSave.Left = panBtn.Width - btnsaveX;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Sub_Add();
        }

        private void Sub_Add()
        {
            FrmDllfiles f = new();
            DialogResult dret = f.ShowDialog();
            if (dret == DialogResult.OK)
            {
                DataTable? dt = f.DllPackDT;
                if (dt == null || dt.Rows.Count == 0) return;
                DataTable m_dt = (DataTable)dgvList.DataSource;
                foreach (DataRow dr in dt.Rows)
                {
                    DataRow[] drs = m_dt.Select($"u8ver={dr["u8ver"]} and name='{dr["name"]}'");
                    if (drs.Length > 0) continue;
                    m_dt.Rows.Add(dr.ItemArray);
                }
                m_dt.DefaultView.Sort = "u8ver asc,name asc";
            }
        }

        private void dgvList_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            panMain.Enabled = false;
            Sub_Del();
            panMain.Enabled = true;
        }

        private void Sub_Del()
        {
            bool flag = dgvList.SelectedRows.Count == 0;
            if (!flag)
            {
                foreach (object obj in dgvList.SelectedRows)
                {
                    DataGridViewRow row = (DataGridViewRow)obj;
                    dgvList.Rows.Remove(row);
                }
            }
        }

        private void btnEmpty_Click(object sender, EventArgs e)
        {
            panMain.Enabled = false;
            Sub_Empty();
            panMain.Enabled = true;
        }

        private void Sub_Empty()
        {
            if (dgvList.SelectedRows.Count == 0) return;
            if (dgvList.DataSource is not DataTable dt || dt.Rows.Count == 0) return;
            dt.Rows.Clear();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            panMain.Enabled = false;
            Sub_Save();
            panMain.Enabled = true;
        }

        private void Sub_Save()
        {
            string projectname = txtProjectname.Text.Trim_Ext();
            string systempath = txtSystempath.Text.Trim_Ext();
            string ver = txtVer.Text.Trim_Ext();
            string desc = txtDesc.Text.Trim_Ext();
            if (projectname.IsNullOrWhiteSpace())
            {
                CommFun.MsgBox("请输入项目名称！", 1);
                txtProjectname.Focus_Ext();
                return;
            }
            if (systempath.IsNullOrWhiteSpace())
            {
                CommFun.MsgBox("请输入项目存储目录名称！", 1);
                txtSystempath.Focus_Ext();
                return;
            }
            if (ver.IsNullOrWhiteSpace()) ver = "1.0";
            if (dgvList.Rows.Count <= 0)
            {
                CommFun.MsgBox("请添加链接文件！", 1);
                btnAdd.Focus_Ext();
                return;
            }

            DataTable dt = (DataTable)dgvList.DataSource;
            if (dt == null || dt.Rows.Count <= 0)
            {
                CommFun.MsgBox("内存表获取错误！", 1);
                btnAdd.Focus_Ext();
                return;
            }
            UiProject ??= new Json_Project();

            if (UiProject.Id.IsNull()) UiProject.Id = CommFun.NewSequentialid();

            UiProject.projectname = projectname;
            UiProject.projectfile = systempath + ".json";

            if (BaseCls.JsonProject != null)
            {
                bool ishave = BaseCls.JsonProject.Exists(x => x.projectname.Equals_Ext(UiProject.projectname) && !x.Id.Equals(UiProject.Id));
                if (ishave)
                {
                    CommFun.MsgBox("项目名称已存在，不允许重复！", 1);
                    txtProjectname.Focus_Ext();
                    return;
                }
                ishave = BaseCls.JsonProject.Exists(x => x.projectfile.Equals_Ext(UiProject.projectfile) && !x.Id.Equals(UiProject.Id));
                if (ishave)
                {
                    CommFun.MsgBox("存放目录名称已存在，不允许重复！", 1);
                    txtSystempath.Focus_Ext();
                    return;
                }
            }
            Json_ProjectInfo ProjectInfo = new()
            {
                ver = ver,
                desc = desc,
                systempath = systempath,
                dlls = []
            };
            foreach (object obj in dt.Rows)
            {
                DataRow dr = (DataRow)obj;
                Json_ProjectDlls? dlls = ModelHelper.DataRowToModel<Json_ProjectDlls>(dr);
                if (dlls != null)
                {
                    ProjectInfo.dlls.Add(dlls);
                }
            }
            string jsonInfo = JsonHelper.Serialize(ProjectInfo);
            BaseCls.WriteLibsJson(UiProject.projectfile, jsonInfo);
            CommFun.MsgBox("项目名称：\r\n" + UiProject.projectname + "\r\n保存成功！", 0);
            DialogResult = DialogResult.OK;
        }
        private void txtSystempath_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox txt = (TextBox)sender;
            char[] chars =
            [
                '\\',
                '/',
                ':',
                '*',
                '?',
                '"',
                '<',
                '>',
                '|'
            ];
            ToolTip tip = new()
            {
                IsBalloon = true,
                ToolTipIcon = ToolTipIcon.Warning,
                ToolTipTitle = "名称不能包含以下字符"
            };
            foreach (char c in chars)
            {
                if (c == e.KeyChar)
                {
                    e.Handled = true;
                    tip.Show("\\/:*?\"<>|", txt, 0, -(txt.Top + txt.Height));
                    return;
                }
            }
            tip.Dispose();
        }

    }
}
